package com.qing.seckill.service.thread;

import com.alibaba.fastjson.JSON;
import com.qing.seckill.entity.OrderRecord;
import com.qing.seckill.entity.TbSeckillGoods;
import com.qing.seckill.entity.TbSeckillOrder;
import com.qing.seckill.mapper.TbSeckillGoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

@Component
public class CreateOrderThread implements Runnable {

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Autowired
	private TbSeckillGoodsMapper goodsMapper;


	@Override
	public void run() {

		String jsonOrderStr = redisTemplate.boundListOps(OrderRecord.class.getSimpleName()).rightPop();
		OrderRecord orderRecord = JSON.parseObject(jsonOrderStr, OrderRecord.class);
		if (Objects.nonNull(orderRecord)) {
			Long id = orderRecord.getId();
			String userId = orderRecord.getUserId();
			TbSeckillGoods seckillGoods = JSON.parseObject((String) redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).get(String.valueOf(id)), TbSeckillGoods.class);

			//3.未售罄，创建订单，已用户id为key存入Redis
			TbSeckillOrder seckillOrder = new TbSeckillOrder();
			seckillOrder.setId(System.currentTimeMillis());
			seckillOrder.setSeckillId(id);
			seckillOrder.setMoney(seckillGoods.getCostPrice());
			seckillOrder.setUserId(userId);
			seckillOrder.setSellerId(seckillGoods.getSellerId());
			seckillOrder.setCreateTime(LocalDateTime.now());
			seckillOrder.setStatus("0");
			redisTemplate.boundHashOps(TbSeckillOrder.class.getSimpleName()).put(userId, JSON.toJSONString(seckillOrder));

			synchronized (CreateOrderThread.class) {
				seckillGoods = JSON.parseObject((String) redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).get(String.valueOf(id)), TbSeckillGoods.class);
				//4.更新库存，判断库存是否售罄
				seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
				if (seckillGoods.getStockCount() <= 0) {
					//5.售罄，同步秒杀商品数据库（TbSeckillGoods），将秒杀商品从Redis中删除
					goodsMapper.updateById(seckillGoods);
					redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).delete(String.valueOf(seckillGoods.getId()));
				} else {
					//6.未售罄，更新Redis中秒杀商品库存
					redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).put(String.valueOf(seckillGoods.getId()), JSON.toJSONString(seckillGoods));
				}
			}
		}

	}
}
